package org.example.rowing.controller;

import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;
import org.example.rowing.controller.util.BaseController;
import org.example.rowing.controller.util.NavigationUtil;
import org.example.rowing.domain.Event;
import org.example.rowing.enums.BoatTypeEnum;
import org.example.rowing.service.EventInfoService;
import org.example.rowing.vo.EventVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
import java.util.Objects;
import java.util.Optional;


@Controller
@Slf4j
public class CKEventInfoController extends BaseController {
    @FXML
    public ComboBox<String> boatTypeComboBox;
    @FXML
    private TextField searchTextField;
    @FXML
    private DatePicker startDatePicker;
    @FXML
    private TableView<EventVO> eventsTable;
    @FXML
    public TableColumn<EventVO, String> categoryColumn;
    public TableColumn<EventVO, String> idColumn;
    @FXML
    private TableColumn<EventVO, String> nameColumn;
    @FXML
    private TableColumn<EventVO, String> startTimeColumn;
    @FXML
    private TableColumn<EventVO, String> endTimeColumn;
    @FXML
    private TableColumn<EventVO, String> locationColumn;
    @FXML
    private TableColumn<EventVO, Void> operationColumn;

    private ObservableList<EventVO> eventList;

    @FXML
    private VBox sideNav;

    @FXML
    private Button btnCKEventInfo;

    @FXML
    private Button addCKEventButton;

    @Autowired
    private EventInfoService eventInfoService;

    @Override
    public void initialize() {
        super.initialize();

        // 设置表格列
        idColumn.setCellValueFactory(cellData -> new SimpleStringProperty(String.valueOf(cellData.getValue().getId())));
        nameColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getName()));
        categoryColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getBoatType()));
        startTimeColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getStartDate()));
        endTimeColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getEndDate()));
        locationColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getLocation()));

        // 设置操作列（修改、删除按钮）
        operationColumn.setCellFactory(col -> new TableCell<>() {
            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);
                if (empty) {
                    setGraphic(null);
                } else {
                    Button modifyButton = new Button("修改");
                    modifyButton.setOnAction(event -> handleModifyEvent(getTableRow().getItem()));

                    Button deleteButton = new Button("删除");
                    deleteButton.setOnAction(event -> handleDeleteEvent(getTableRow().getItem()));

                    HBox hBox = new HBox(modifyButton, deleteButton);
                    setGraphic(hBox);
                }
            }
        });
        // 初始化赛事列表（默认展示一些数据）
        List<String> boatTypes = List.of("皮艇", "划艇");
        boatTypeComboBox.setItems(FXCollections.observableArrayList(boatTypes));
        // 默认选中第一个
        boatTypeComboBox.getSelectionModel().select(0);
        updateTableForBoatType(boatTypeComboBox.getSelectionModel().getSelectedItem());
        // 为下拉框添加监听器，用户选择其他赛事时更新表格数据
        boatTypeComboBox.valueProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue != null) {
                updateTableForBoatType(newValue);
            }
        });
    }

    private void updateTableForBoatType(String boatType) {
        // 将过滤后的列表更新到表格
        eventList = FXCollections.observableArrayList(eventInfoService.showEventsByType(BoatTypeEnum.fromDisplayName(boatType)));
        eventsTable.setItems(eventList);
        eventsTable.refresh();
    }

    @Override
    protected Button getButton() {
        return btnCKEventInfo;
    }

    // 搜索事件
    @FXML
    public void handleSearch() {
        String boatType = boatTypeComboBox.getSelectionModel().getSelectedItem();
        String query = searchTextField.getText().trim();  // 获取输入的赛事名称
        LocalDate startDate = startDatePicker.getValue();  // 获取选择的开始日期

        log.info("搜索栏内容为：{} {}", query, startDate);

        Event event = new Event();
        event.setBoatTypeEnum(BoatTypeEnum.fromDisplayName(boatType));
        if (!query.isEmpty()) {
            event.setName(query);
        }
        if (startDate != null) {
            event.setStartDate(startDate.toString());
        }

        // 将过滤后的列表更新到表格
        eventList.setAll(eventInfoService.showSearchedEvents(event));
        eventsTable.refresh();
    }

    @FXML
    public void handleClearSearch() {
        // 清空搜索框内容
        String boatType = boatTypeComboBox.getSelectionModel().getSelectedItem();
        searchTextField.clear();
        startDatePicker.setValue(null); // 清空日期选择器

        // 重新显示所有赛事
        eventList.setAll(eventInfoService.showEventsByType(BoatTypeEnum.fromDisplayName(boatType)));
        eventsTable.refresh();
    }

    // 添加赛事事件
    @FXML
    public void handleAddEvent() {
        // 打开添加赛事界面的逻辑
        log.info("点击添加赛事按钮");
        NavigationUtil.showPopup(
                NavigationUtil.viewMap.get(addCKEventButton.getId()),
                "添加赛事",
                addCKEventButton.getScene().getWindow(),
                controller -> {
                    if (controller instanceof UpdateCKEventController) {
                        ((UpdateCKEventController) controller).initialize(null);
                    }
                }
        );
        // 刷新展示内容
        String boatType = boatTypeComboBox.getSelectionModel().getSelectedItem();
        eventList.setAll(eventInfoService.showEventsByType(BoatTypeEnum.fromDisplayName(boatType)));
        eventsTable.refresh();
    }

    // 修改赛事事件
    public void handleModifyEvent(EventVO event) {
        // 进行修改赛事操作
        log.info("修改赛事: {}", event.getId());
        NavigationUtil.showPopup(
                NavigationUtil.viewMap.get(addCKEventButton.getId()),
                "修改赛事",
                eventsTable.getScene().getWindow(),
                controller -> {
                    if (controller instanceof UpdateCKEventController) {
                        ((UpdateCKEventController) controller).initialize(event);
                    }
                }
        );
        // 刷新展示内容
        String boatType = boatTypeComboBox.getSelectionModel().getSelectedItem();
        eventList.setAll(eventInfoService.showEventsByType(BoatTypeEnum.fromDisplayName(boatType)));
        eventsTable.refresh();
    }

    // 删除赛事事件
    public void handleDeleteEvent(EventVO event) {
        Optional<ButtonType> result = showConfirmationDialog();
        // 删除赛事操作
        if (result.isPresent() && Objects.equals(result.get().getText(), "确定")) {
            eventInfoService.deleteEvent(event.getId());
            log.info("删除赛事: {}", event.getName());
            // 刷新展示内容
            String boatType = boatTypeComboBox.getSelectionModel().getSelectedItem();
            eventList.setAll(eventInfoService.showEventsByType(BoatTypeEnum.fromDisplayName(boatType)));
            eventsTable.refresh();
        } else {
            log.info("取消删除");
        }
    }

    @FXML
    public void handleNavButtonClick(ActionEvent event) throws IOException {
        log.info("当前触发事件为：{}",event);
        Button clickedButton = (Button) sideNav.getScene().getFocusOwner();
        NavigationUtil.navigateToScene(
                event,
                NavigationUtil.viewMap.get(clickedButton.getId()),
                "皮划艇管理");
    }

    @FXML
    public void handleRowingClick(ActionEvent event) throws Exception {
        log.info("切换到赛艇界面");
        NavigationUtil.navigateToScene(
                (Stage) sideNav.getScene().getWindow(),
                "/fxml/rowingViews/EventInfoView.fxml",
                "赛艇管理");
    }
}
